<?php

namespace App\Repositories\Auth;


use App\Models\Auth\Admin;
use App\Models\Auth\Role;
use App\Repositories\Repository;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use function PHPSTORM_META\type;


/**
 *
 */
class AdminRepository extends Repository
{

    /**
     * @var \Laravel\Lumen\Application|mixed
     */
    private $redis;

    /**
     * @var int token有效时间
     */
    private $expire_in = 86400;

    public function __construct(Request $request)
    {
        parent::__construct($request);
        $this->redis = app('phpredis');
    }


    public function index($params)
    {
        $admins = Admin::query()->with(['roles' => function ($query) use ($params) {
            $query->when(!empty($params['role_id']), function ($query) use ($params) {
                $query->where('role_id', $params['role_id']);
            });
        }])->when(!empty($params['tel']), function ($query) use ($params) {
            $query->where('tel', $params['tel']);
        })->when(!empty($params['name']), function ($query) use ($params) {
            $query->where('name', 'like', $params['name'] . '%');
        })->paginate($this->page_size, ['*'], 'page', $this->page);

        return $this->respondWith($admins);
    }


    public function show($admin_id)
    {
        $admin = Admin::query()->with('roles')->where('admin_id', $admin_id)->first();
//        if($admin->roles){
//            $role_ids = [];
//            foreach ($admin->roles as $role) {
//                $role_ids[] = $role->role_id;
//            }
//            $admin->roles = $role_ids;
//        }
        return $this->respondWith($admin);
    }

    /**
     * 管理员登录
     *
     * @author Pako
     * @createTime 2018/8/19 16:30
     * @param $tel
     * @param $password
     * @param $ip
     * @param bool $force
     * @return mixed
     */
    public function login($tel, $password, $ip, $force = false)
    {
        $admin = Admin::query()->with('roles')->where('tel', $tel)->first();
        if (!$admin) {
            return $this->respondError(10300);
        }
        //较验密码
        $this->checkPassword($password, $admin->password, $tel);

        //判断是否在线，单点登录
        $this->checkOnling($admin, $force);

        //获取权限
        $role_ids = $this->getRolesIds($admin->roles);
        $permissions = $this->getPermissionsId($role_ids);
        $roles = [];
        if (count($admin->roles)) {
            foreach ($admin->roles as $role) {
                $roles[] = $role->key_name;
            }
        }
        if (count($roles) == 0) {
            $roles[] = 'geust';
        }
        //此处简单生成token，可以加上时间IP地址等来验证token盗用
        $token = uuid();

        $data = [
            'admin_name' => $admin->name,
            'admin_id' => $admin->admin_id,
            'permissions' => $permissions,
            'supper' => $admin->supper,
            'avartar' => $admin->avartar,
            'expire_in' => $this->expire_in,
            'roles' => $roles
        ];

        //写入缓存
        $this->infoCache($data, $token);

        //更新登录信息
        $admin->login_ip = $ip;
        $admin->remember_token = $token;
        $admin->save();

        //操作日志
        log_done($admin->admin_id, $admin->name, '管理员登录', $ip);
        $data['token'] = $token;
        $data['token_type'] = 'Bearer';
        unset($data['permissions']);
        unset($data['supper']);
        return $this->respondWith($data);

    }

    /**
     *
     * 获取管理员信息
     * author Paco
     * createTime 2019/1/17 11:41
     * @return \Illuminate\Http\JsonResponse|mixed
     */
    public function info()
    {
        $data = $this->getAdmin(true);
        return $this->respondWith($data);
    }

    /**
     *
     * loginOut
     * @author Paco
     * @createTime 2018/6/13 10:18
     * @param $token
     * @return mixed
     * @throws \Exception
     */
    public function loginOut()
    {
        $token = $this->getToken();
        $this->log_done('管理员退出');
        $this->redis->del('token_' . $token);
        return $this->respondSuccess();
    }

    /**
     *
     * 修改管理员
     * @author Paco
     * @createTime 2018/8/22 10:19
     * @param $data
     * @return mixed
     */
    public function save($data)
    {
        //$data = array_filter($data,'my_array_filter');
        if (isset($data['password'])) {
            $data['password'] = Hash::make($data['password']);
        }
        $admin = Admin::query()->where('admin_id', $data['admin_id'])->first();
        $role_data = [];
        foreach ($data['roles'] as $role) {
            $role_data[] = ['admin_id' => $admin->admin_id, 'role_id' => $role];
        }
        if ($admin) {
            $admin->fill($data)->save();
            DB::table('admin_role')->where('admin_id', $admin->admin_id)->delete();
            if (count($role_data)) {
                DB::table('admin_role')->insert($role_data);
            }
            $this->log_done('编辑管理员', $data);

        }
        return $this->respondWith($admin);
    }

    /**
     *
     * 只更新管理员内容（无权限修改）
     * @author Paco
     * @createTime 2018/8/22 10:37
     * @param $data
     * @return mixed
     */
    public function simpleSave($data)
    {
        if (isset($data['password'])) {
            $data['password'] = Hash::make($data['password']);
        }
        $admin = Admin::query()->where('admin_id', $data['admin_id'])->first();
        if ($admin) {
            $admin->fill($data)->save();
            $this->log_done('编辑管理员', $data);
        }
        return $this->respondWith($admin);
    }


    /**
     *
     * 添加管理员
     * @author Paco
     * @createTime 2018/8/22 10:24
     * @param $data
     * @return mixed
     */
    public function store($data)
    {
        if (isset($data['password'])) {
            $data['password'] = Hash::make($data['password']);
        }
        $role_data = [];
        $admin = Admin::query()->create($data);
        foreach ($data['roles'] as $role) {
            $role_data[] = ['admin_id' => $admin->admin_id, 'role_id' => $role];
        }

        if ($admin) {
            if (count($role_data)) {
                DB::table('admin_role')->insert($role_data);
            }
            $data['admin_id'] = $admin->admin_id;
            $this->log_done('添加管理员', $data);
        }
        return $this->respondWith($admin);
    }


    public function del($ids)
    {
        try {
            if ($ids) {
                if (gettype($ids) != 'array') {
                    $ids = explode(',', $ids);
                }
                DB::table('admin_role')->whereIn('admin_id', $ids)->delete();
                Admin::query()->whereIn('admin_id', $ids)->where('supper',0)->delete();
            }
            return $this->respondSuccess();
        } catch (\Exception $e) {
            return $this->respondError(10107);
        }


    }


    /*
     * ==========================================================================================
     *                                    私有方法
     * ==========================================================================================
    */

    /**
     * 验证密码
     *
     * @author Pako
     * @createTime 2018/8/19 11:00
     * @param $input_pwd
     * @param $db_pwd
     * @param $tel
     * @return mixed
     */
    private function checkPassword($input_pwd, $db_pwd, $tel)
    {
        $key = config('cache.admin.login') . 'failed_' . $tel;
        if (!Hash::check($input_pwd, $db_pwd)) {
            $this->redis->incr($key);
            $this->redis->expire($key, 3600);
            return $this->throwRespondError(10301);
        } else {
            $this->redis->del($key);
        }
        return true;
    }

    /**
     * 获取会员角色ID
     *
     * @author Pako
     * @createTime 2018/8/19 16:28
     * @param $roles
     * @return array
     */
    private function getRolesIds($roles)
    {
        $role_ids = [];
        foreach ($roles as $role) {
            $role_ids[] = $role->role_id;
        }
        return $role_ids;
    }


    /**
     * 获取角色权限ID
     *
     * @author Pako
     * @createTime 2018/8/19 11:32
     * @param $role_id
     * @return array
     */
    private function getPermissionsId($role_id)
    {
        $roles = Role::query()->with('permissions')->whereIn('role_id', $role_id)->get();
        $permission_names = [];
        foreach ($roles as $role) {
            foreach ($role->permissions as $permission) {
                $permission_names[] = $permission->name;
            }
        }
        return array_unique($permission_names);
    }

    /**
     * 登录信息存入redis缓存
     *
     * @author Pako
     * @createTime 2018/8/19 16:27
     * @param $data
     */
    private function infoCache($data, $token)
    {
        $key = 'token_' . $token;
        $this->redis->setex($key, $this->expire_in, json_encode($data));
    }

    /**
     * 判断是否已登录，与强制登录
     *
     * @author Pako
     * @createTime 2018/8/19 16:28
     * @param $admin
     * @param $force
     * @return mixed
     */
    private function checkOnling($admin, $force)
    {
        $key = 'token_' . $admin->remember_token;
        if ($this->redis->exists($key)) {
            if ($force) {
                $this->redis->del($key);
            } else {
                return $this->throwRespondError(10308);
            }
        }
        return true;
    }


}

